#include "shelf.h"

Shelf::Shelf(int maxBookCount, QObject *parent) :
    maxBookCount(maxBookCount), QObject(parent)
{

}


bool Shelf::tryTakeBookForRead(int &index){
    QVector<Book*>::iterator it = books.begin();
    int i = 0;
    while(it != books.end()){
        if((*it)->tryLock()){
            index = i;
            return true;
        }
        ++it;
        ++i;
    }
    return false;
}

bool Shelf::tryTakeBookForEdit(QString writerName, int &index){
    QVector<Book*>::iterator it = books.begin();
    int i = 0;
    while(it != books.end()){
        if((*it)->writerName == writerName && (*it)->tryLock()){
            index = i;
            return true;
        }
        ++it;
        ++i;
    }
    return false;
}

void Shelf::tryPutBook(int index){
    books[index]->unlock();
}

bool Shelf::tryPutNewBook(QString writerName){
    if(books.size() < maxBookCount){
        books.push_back(new Book(writerName));
        return true;
    }
    return false;
}


